import { pathToCamel } from '@/utils/tool'
import { RouteRecordRaw } from 'vue-router'
import { defineStore } from 'pinia'
const layoutModules = import.meta.glob('/src/views/**/*.vue');
// 根据路径，动态获取vue组件
const getDynamicComponent = (path: string): any => {
    const component = layoutModules[`/src/views/${path}.vue`]
    if (!component) {
        console.error('组件不存在，路径为：', path)
    }
    return component
}

const hasPermission = (menu: any, permissions: string[]) => {
    if (menu && menu.permissions && menu.permissions.length) {
        return menu.permissions.some((key: string) => permissions.includes(key))
    } else {
        return true
    }
}



const filterMenuList = (menuList: any, permissions: string[]): any => {
    const newMenuList: any[] = []
    menuList.forEach((menu: any) => {
        if (hasPermission(menu, permissions)) {
            const menuItem = {
                ...menu,
                children: []
            }

            // 有子菜单的情况
            if (menu.children && menu.children.length > 0) {
                menuItem.children?.push(...filterMenuList(menu.children, permissions))
            }

            newMenuList.push(menuItem)
        }
    })

    return newMenuList
}


// 根据菜单列表，生成路由数据
const generateRoutes = (menuList: any): RouteRecordRaw[] => {
    const routerList: RouteRecordRaw[] = []

    menuList.forEach((menu: any) => {
        let component
        let path = menu.path ? menu.path : '/' + menu.url

        if (
            menu.children &&
            menu.children.length &&
            menu.children.filter((child: any) => !child.hideMenu).length
        ) {
            component = () => import('@/layout/index.vue')
        } else {
            component = getDynamicComponent(menu.url.replace(/\_/g, '-'))
        }

        const route: RouteRecordRaw = {
            path: path,
            name: pathToCamel(path),
            component,
            children: [],
            meta: {
                title: menu.name,
                icon: menu.icon,
                id: '' + menu.id,
                cache: true,
                affix: menu.id === 1000,
                _blank: menu.openStyle === 1,
                breadcrumb: [],
                hideMenu: menu.hideMenu || false,
                permissions: menu.permissions,
                equipmentTypeId: menu.equipmentTypeId
            }
        }

        // 有子菜单的情况
        if (menu.children && menu.children.length > 0) {
            route.children?.push(...generateRoutes(menu.children))
        }

        routerList.push(route)
    })

    return routerList
}
